<template>
  <div style="display: flex; height: 100%;">
    <!-- 左侧岗位列表 -->
    <div style="width: 20%; border-right: 1px solid #eee; padding: 10px;">
      <el-menu :default-active="selectedPost" @select="handlePostSelect"
        style="border-right: none; background-color: transparent;" class="custom-menu">
        <el-menu-item v-for="post in uniquePosts" :key="post" :index="post">
          {{ post }}
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧表格和上传按钮 -->
    <div style="flex: 1; padding: 10px;">
      <!-- 上传按钮 -->
      <div style="display: flex; justify-content: flex-end; margin-bottom: 16px;">
        <el-button @click="uploadDialogVisible = true">上传简历</el-button>
      </div>

      <!-- 简历表格 -->
      <el-table :data="filteredTableData" style="width: 100%">
        <el-table-column prop="userid" label="用户ID" width="120" />
        <!-- <el-table-column prop="reid" label="简历岗位" /> -->
        <el-table-column prop="name" label="简历名称" />
        <!-- <el-table-column prop="scheme" label="方案" /> -->
        <!-- <el-table-column prop="content" label="简历链接" /> -->
        <el-table-column prop="notes" label="备注" />
        <el-table-column prop="todate" label="创建时间" />
        <el-table-column label="查看简历" width="120">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="简历解析" width="120">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="handleViewDetail(scope.row)">
              解析
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="删除简历" width="120">
          <template #default="scope">
            <el-button type="text" class="JNPF-table-delBtn" @click="handleDel(scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination background layout="prev, pager, next" :total="pagination.total" :page-size="pagination.pageSize"
        :current-page="pagination.page" @current-change="handlePageChange" style="margin-top: 16px;" />
    </div>

    <!-- 上传简历弹窗 -->
    <el-dialog title="上传简历" :visible.sync="uploadDialogVisible" width="500px">
      <el-form :model="uploadForm" label-width="120px">
        <el-form-item label="上传类型">
          <el-radio-group v-model="uploadForm.type">
            <el-radio label="overwrite">覆盖原有版本</el-radio>
            <el-radio label="new">新建简历 ID</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 选择已有简历进行覆盖 -->
        <el-form-item label="选择已有简历" v-if="uploadForm.type === 'overwrite'">
          <el-select v-model="uploadForm.selectedResumeId" placeholder="请选择简历">
            <el-option v-for="item in filteredTableData" :key="item.reid" :label="`${item.name}（方案${item.scheme}）`"
              :value="item.reid" />
          </el-select>
        </el-form-item>

        <!-- 新建简历名称 -->
        <el-form-item label="简历名称" v-if="uploadForm.type === 'new'">
          <el-input v-model="uploadForm.name" placeholder="请输入简历名称" />
        </el-form-item>

        <el-form-item label="上传文件">
          <el-upload class="upload-resume" drag :show-file-list="true" :auto-upload="false"
            :on-change="handleFileChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">仅支持 PDF 或 DOC 文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="uploadForm.notes" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResume">确认上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getResumeList, createResume, updateResume } from '@/api/example/resume'
import OSS from 'ali-oss'
import request from '@/utils/request'

export default {
  name: 'ResumeList',
  data() {
    return {
      tableData: [],
      selectedPost: '',
      pagination: { page: 1, pageSize: 10, total: 0 },
      uploadDialogVisible: false,
      uploadForm: {
        type: 'overwrite',
        selectedResumeId: '',
        name: '',
        file: null,
        notes: ''
      },
      ossConfig: {
        region: 'oss-cn-wuhan-lr',
        accessKeyId: 'xxx',
        accessKeySecret: 'xxx',
        bucket: 'mangopdf',
      },
    }
  },
  computed: {
    uniquePosts() {
      return [...new Set(this.tableData.map(item => item.reid))];
    },
    filteredTableData() {
      return this.selectedPost
        ? this.tableData.filter(item => item.reid === this.selectedPost)
        : [];
    },
    currentUser() {
      return this.$store.state.user.userInfo || {};
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      getResumeList({
        page: this.pagination.page,
        pageSize: this.pagination.pageSize
      }).then(res => {
        const data = res.data || {};
        this.tableData = Array.isArray(data.list) ? data.list : [];
        if (data.pagination) {
          this.pagination.total = data.pagination.total || 0;
          this.pagination.page = data.pagination.currentPage || 1;
          this.pagination.pageSize = data.pagination.pageSize || 10;
        }
        if (!this.selectedPost && this.uniquePosts.length > 0) {
          this.selectedPost = this.uniquePosts[0];
        }
      });
    },
    handlePostSelect(post) {
      this.selectedPost = post;
    },
    handlePageChange(page) {
      this.pagination.page = page;
      this.fetchData();
    },
    handleViewDetail(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在下载简历 PDF...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        const resumeId = row.reid;
        const downloadUrl = `https://your-domain.com/api/resume/download/${resumeId}`;
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = `resume_${resumeId}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        this.$message.error('下载简历失败');
      } finally {
        loading.close();
      }
    },
    handleFileChange(file) {
      this.uploadForm.file = file.raw;
    },
    async submitResume() {
      // 文件验证逻辑...
    },
    async uploadToOSS(blob) {
      const client = new OSS(this.ossConfig);
      const fileName = `interview-reports/${this.currentUser.id || 'anonymous'}/${Date.now()}.pdf`;
      const result = await client.put(fileName, blob, {
        headers: {
          'Content-Type': this.uploadForm.file.type,
          'Content-Disposition': `inline`
        }
      });
      return result.url;
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        console.log('删除 ID:', id);
        request({
          url: `/api/example/Whu_resume/${id}`,
          method: 'DELETE'
        }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            onClose: () => {
              this.fetchData()
            }
          });
        })
      }).catch(() => {
      });
    },
  }
}
</script>

<style scoped>
.upload-resume {
  width: 100%;
}

/* 所有文字默认黑色 */
.custom-menu .el-menu-item {
  color: #554a2f !important;
  font-size: 14px;
  height: 60px !important;
  /* 调高菜单项高度 */
  line-height: 60px !important;
  /* 文字垂直居中 */
  transition: font-size 0.2s ease, background-color 0.3s ease;
}


/* 鼠标悬停时字体变大 */
.custom-menu .el-menu-item:hover {
  font-size: 16px;
  background-color: transparent !important;
}

/* 选中状态背景淡黄色，文字依然黑色 */
.custom-menu .el-menu-item.is-active {
  background-color: #f0e6d2 !important;
  /* 淡黄色 */
  color: #635637 !important;
  /* border: #c6ab6d 1px solid; */
  border-radius: 10px;
}
</style>
